package com.bolong.gmgc.redis;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bolong.gmgc.JPushUtils;
import com.bolong.gmgc.UUIDUtils;
import com.bolong.gmgc.bean.record.BerthSign;
import com.bolong.gmgc.bean.record.BerthSignQuery;
import com.bolong.gmgc.dao.record.BerthSignMapper;

import redis.clients.jedis.JedisPubSub;

@Service
@Transactional
public class KeyExpiredListener extends JedisPubSub {

	@Autowired
	private BerthSignMapper berthSignMapper;

	@Override
	public void onPSubscribe(String pattern, int subscribedChannels) {
		System.out.println("onPSubscribe " + pattern + " " + subscribedChannels);
	}

	@Override
	public void onPMessage(String pattern, String channel, String message) {
//		System.out.println(message);
		int indexOf = message.indexOf(":");
		if (indexOf != -1) {
			String[] split = message.split(":");
			if (split.length > 1) {
				String token = split[0];
				String flag = split[1];
				if (flag.equals("ZONE_TOKEN")) {
					try {
						BerthSignQuery query = new BerthSignQuery();
						query.createCriteria().andTokenEqualTo(token).andSignTypeGreaterThan(1);
						List<BerthSign> list2 = berthSignMapper.selectByExample(query);
						if (list2 == null || list2.size() == 0) {
							query.clear();
							query.createCriteria()//
									.andTokenEqualTo(token);//
							List<BerthSign> list = berthSignMapper.selectByExample(query);
							if (list != null && list.size() > 0) {
								String empId = list.get(0).getEmpId();
								// 推送自动签出
//								JPushUtils.setAppKey(2);
								JPushUtils.sendPushByAliasAloneAlert(empId, "token失效");
								System.out.println(empId + "token失效");
								// 保存一条签出记录
								BerthSign berthSign = new BerthSign();
								berthSign.setId(UUIDUtils.getId());
								berthSign.setEmpId(empId);
								berthSign.setSignTime(new Date());
								berthSign.setSignType(3);
								berthSign.setToken(token);
								berthSign.setZoneId(list.get(0).getZoneId());
								berthSign.setEquipmentId(list.get(0).getEquipmentId());
								berthSignMapper.insertSelective(berthSign);
							}
						}
					} catch (Exception e) {
						// 输出错误信息
						// 错误信息写入日志
						System.out.println(e);
					}
				}
			}
		}
	}
}
